class Manager < ActiveRecord::Base
  # unencrypted password
  attr_accessor :m_password

  # validation
  validates_presence_of     :m_name
  validates_length_of       :m_password, :within => 4..40,
                                       :if => :m_password_required? 
  
  validates_confirmation_of :m_password, :if => :m_password_required?
  
  # callbacks
  before_save :encrypt_password 

  # encrypts given password using salt
  def self.encrypt(pass, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{pass}--")
  end

 # authenticate by email/password 
  def self.authenticate(email, pass)
    manager = find_by_m_email(email)
    manager && manager.authenticated?(pass) ? manager : nil
  end

  # does the given password match the stored encrypted password
  def authenticated?(pass)
    encrypted_password == manager.encrypt(pass, salt)
  end
  protected

  # before save - create salt, encrypt password
  def encrypt_password 
    return if m_password.blank?
    if new_record?
      self.salt = Digest::SHA1.hexdigest("--#{Time.now}--")
    end
    self.encrypted_password = manager.encrypt(m_password, salt)  
  end

  # no encrypted password yet OR password attribute is set
  def m_password_required?
    encrypted_password.blank? || !m_password.blank?
  end
end
